﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using mshtml;


namespace PriceWatcher
{
    public partial class frmWeb : Form
    {
        private HtmlElement divSelectL,divSelectR,divSelectT,divSelectB;
        private bool isTarget = true;
        public delegate void NewTargetEventHandler(Object sender, NewTargetEventArgs e);
        public event NewTargetEventHandler newTarget;

        public frmWeb()
        {
            InitializeComponent();
            this.statusLabel.Text = "请在地址栏输入网址";
            this.textUrl.Text = "请输入网址";
            this.textUrl.Focus();
        }

        private void textUrl_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                string url = textUrl.Text;
                //begin with http:// or https:// ,no case.
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"http(s?)://(\S)+", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                if (!reg.IsMatch(url))
                    url = @"http://" + url;
                Uri uri = null;
                if (Uri.IsWellFormedUriString(url, System.UriKind.Absolute))
                {
                    uri = new Uri(url);
                    webBrowser1.Navigate(uri);
                    webBrowser1.Focus();
                }
                else
                    MessageBox.Show("输入的网址有误", "网址有误", MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string url = e.Url.ToString().ToLower();
            //begin with http:// or https:// ,no case.
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"http(s?)://(\S)+", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (!reg.IsMatch(url)) return;  //AJAX
            if (e.Url.AbsolutePath != webBrowser1.Url.AbsolutePath) return;  //frame or iframe
            // not AJAX or frame, then it is really load completed

            textUrl.Text = webBrowser1.Url.AbsoluteUri;
            statusLabel.Text = "完成";

            HtmlDocument doc = webBrowser1.Document;
            divSelectL = doc.CreateElement("div");
            doc.Body.AppendChild(divSelectL);
            divSelectR = doc.CreateElement("div");
            doc.Body.AppendChild(divSelectR);
            divSelectT = doc.CreateElement("div");
            doc.Body.AppendChild(divSelectT);
            divSelectB = doc.CreateElement("div");
            doc.Body.AppendChild(divSelectB);
            doc.MouseOver += new HtmlElementEventHandler(dom_MouseOver);
            doc.Click += new HtmlElementEventHandler(dom_MouseClick);
        }

        private void dom_MouseOver(object sender,HtmlElementEventArgs e)
        {
            if (isTarget)
            {
                HtmlElement ele = e.ToElement;
                if (ele == divSelectL || ele == divSelectR || ele == divSelectT || ele == divSelectB) return;
                IHTMLElement currElement = ele.DomElement as IHTMLElement;
                Rectangle r = getAbsPosition(currElement);
                int l, t, w, h;
                string strtmp = @"position: absolute; left: {0}px; top: {1}px; width: {2}px; height: {3}px; border-style : solid; border-width: 1px; border-color: red; background-color: red; font-size:1px; overflow: hidden";
                l = r.X;
                t = r.Y;
                w = 1;
                h = r.Height;
                string style = string.Format(strtmp, l, t, w, h);
                divSelectL.Style = style;
                l = l+r.Width;
                style = string.Format(strtmp, l, t, w, h);
                divSelectR.Style = style;
                l = r.X;
                w = r.Width;
                h = 1;
                style = string.Format(strtmp, l, t, w, h);
                divSelectT.Style = style;
                t = r.Y+r.Height;
                style = string.Format(strtmp, l, t, w, h);
                divSelectB.Style = style;
                string path = currElement.tagName;
                IHTMLElement tmp = currElement.parentElement;
                while (tmp != null)
                {
                    path += "<" + tmp.tagName;
                    tmp = tmp.parentElement;
                }
                statusLabel.Text = path;
            }
        }

        private void dom_MouseClick(object sender, HtmlElementEventArgs e)
        {
            if (isTarget)
            {
                HtmlDocument doc = webBrowser1.Document;
                HtmlElement ele=doc.GetElementFromPoint(e.ClientMousePosition);
                if (ele == divSelectL || ele == divSelectR || ele == divSelectT || ele == divSelectB) return;
                IHTMLElement node=ele.DomElement as IHTMLElement;
                checkBox1.Checked = false;
                isTarget = false;
                int i = node.sourceIndex;
                if (i > (divSelectB.DomElement as IHTMLElement).sourceIndex) i -= 4;
                statusLabel.Text = "已经选取了#" + i + "元素<" + node.tagName + ">";
                string tmp = node.innerText;
                if (tmp == null) tmp = "0";
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"^[-+]?[0-9]*.?[0-9]+$");
                if (!reg.IsMatch(tmp)) tmp = "0";
                NewTargetEventArgs inf = new NewTargetEventArgs(textUrl.Text, i, Convert.ToDecimal(tmp));
                OnNewTarget(inf);
                e.ReturnValue = false;
            }
            else
                e.ReturnValue=true;
        }

        private void OnNewTarget(NewTargetEventArgs e)
        {
            if (newTarget != null)
                newTarget(this, e);
        }

        private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            statusLabel.Text = "正在打开" + e.Url.AbsoluteUri;
        }

        private Rectangle getAbsPosition(IHTMLElement e)
        {
            Rectangle r=new Rectangle();
            if (e != null)
            {
                r.X = e.offsetLeft;
                r.Y = e.offsetTop;
                r.Height = e.offsetHeight;
                r.Width = e.offsetWidth;
                e = e.offsetParent;
                while (e != null)
                {
                    r.X += e.offsetLeft;
                    r.Y += e.offsetTop;
                    e = e.offsetParent;
                }
            }
            return r;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            isTarget = checkBox1.Checked;
        }
    }
}
